﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using WeBlog.Interfaces;
using WeBlog.Repositories;

namespace WeBlog.Models
{
    public class ManagePostsViewModel : GridModel<Post>
    {
        private readonly PostRepository _postRepository;
        private readonly User _currentUser;

        public string Query { get; set; }
        public IEnumerable<SelectListItem> Authors { get; set; }
        public int? AuthorId { get; set; }
        

        public ManagePostsViewModel(GridSettings settings, IUnitOfWork unitOfWork, User user ) :
            base(settings)
        {
            _postRepository = new PostRepository(unitOfWork);
            var userRepository = new UserRepository(unitOfWork);
            _currentUser = user;

            settings.DefaultPageSize = 25;
            settings.DefaultSortColumn = "PublishDate";

            if (user.IsInRole(Role.Admin) || user.IsInRole(Role.Editor))
            {
                Authors = userRepository.FindAuthors()
                    .Where(x => x.Posts.Any())
                    .ToList()
                    .Select(x => new SelectListItem {Text = x.FullName, Value = x.UserId.ToString()});
            }
            else
            {
                Authors = new List<SelectListItem>() { new SelectListItem { Text = user.FullName, Value = user.UserId.ToString(), Selected = true } };
            }
        }

        public override IQueryable<Post> GetSuperSet()
        {
            var query = _postRepository.FindAll();
            
            if( String.IsNullOrWhiteSpace(Query) == false )
            {
                query = query.Where( x => 
                            x.Title.Contains(Query) || 
                            x.Content.Contains(Query) ||
                            x.Author.FirstName.Contains(Query) || 
                            x.Author.LastName.Contains(Query));
            }

            if( _currentUser.IsInRole(Role.Subscriber) || _currentUser.IsInRole(Role.Author))
            {
                query = query.Where(x => x.AuthorId == _currentUser.UserId);
            }

            if (AuthorId != null)
                query = query.Where(x => x.Author.UserId == AuthorId);

            return query.OrderByDescending(x => x.PublishDate);
        }
    }
}